/**
 * @fileOverview 常用工具封装-1
 * @author liufeifei@coohua.com
 * @author 电话：18612485334
 * @copyright 刘非非
 */

/**
 * 时间戳格式化
 * 依赖evenNum方法
 * @param  {number} timestamp 时间戳
 * @return {string}           例：2018-08-08
 */
function fromatDate(timestamp) {
    // 时间戳检测，js中转换要以毫秒为单位
    timestamp = String(timestamp).length == 13 ? timestamp : timestamp * 1000;
    var sDate = new Date(timestamp); //日期
    var sYear = sDate.getFullYear(); //年
    var sMonth = sDate.getMonth() + 1; //月
    var sDay = sDate.getDate(); //日
    var sHour = sDate.getHours(); //小时
    var sMinute = sDate.getMinutes(); //分钟
    var sSecond = sDate.getSeconds(); //秒
    var mSecond = sDate.getMilliseconds(); //毫秒
    return `${sYear}-${evenNum(sMonth)}-${evenNum(sDay)} ${evenNum(sHour)}:${evenNum(sMinute)}:${evenNum(sSecond)}`;
}

/**
 * 双数显示数字
 * @param  {number} n 要格式的数字
 * @return {number}   返回双数格式数字
 */
function evenNum(n) {
    return /^\d\d$/.test(n) ? '' + n : '0' + n;
}

/**
 * 查询字符串转对象
 * @return {object} 返回对象
 */
function getQueryStringArgs() {
    var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
        args = {},
        items = qs.length ? qs.split("&") : [],
        item = null,
        name = null,
        value = null,
        i = 0,
        len = items.length;
    for (i = 0; i < len; i++) {
        item = items[i].split("=");
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
        if (name.length) { args[name] = value }
    }
    return args;
}

/**
 * axios的get请求
 * @param  {string}   url       url请求地址
 * @param  {object}   data      请求参数
 * @param  {object}   isLoading 是否启动全局loading，默认false
 * @param  {object}   vm        vue对象，默认为this
 * @param  {Function} callback  回调函数
 * @return {empty}              空
 */
function requestGet(url, data, isLoading = false, vm = this) {
    // 启动loading
    let loading = '';
    if (isLoading) {
        loading = vm.$loading({
            lock: true,
            text: "加载中...",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.7)"
        })
    }
    return new Promise((resolve, reject) => {
        vm.$http.get(url, {
                params: data,
            })
            .then(response => {
                var status = response.status;
                if (status >= 200 && status < 300 || status == 304) {
                    resolve(response);
                    // 关闭loading
                    loading.close();
                } else {
                    reject(response);
                    // 关闭loading
                    loading.close();
                }
            })
            .catch(error => {
                reject(error);
                // 关闭loading
                loading.close();
            });
    })
}

/**
 * axios的post请求
 * @param  {object}   vm        vue对象
 * @param  {string}   url       请求地址
 * @param  {object}   data      请求参数
 * @param  {object}   isLoading 是否启动全局loading，默认false
 * @param  {object}   vm        vue对象，默认为this
 * @param  {Function} callback  回调函数
 * @return {empty}              空
 */
function requestPost(url, data, isLoading = false, vm = this) {
    // 启动loading
    let loading = '';
    if (isLoading) {
        loading = vm.$loading({
            lock: true,
            text: "加载中...",
            spinner: "el-icon-loading",
            background: "rgba(255, 255, 255, 0.7)"
        })
    }
    return new Promise((resolve, reject) => {
        vm.$http.post(url, data)
            .then(response => {
                var status = response.status;
                if ((status >= 200 && status < 300) || status == 304) {
                    resolve(response);
                    // 关闭loading
                    loading.close();
                } else {
                    reject(response);
                    // 关闭loading
                    loading.close();
                }
            })
            .catch(error => {
                reject(error);
                // 关闭loading
                loading.close();
            });
    })
}

/**
 * 获取当前日期前n天的日期
 * @param  {number} n 提前天数
 * @return {string}   格式化的时间，即：2018-08-08
 */
function getBeforeDate(n) {
    var n = n;
    var d = new Date();
    var year = d.getFullYear();
    var mon = d.getMonth() + 1;
    var day = d.getDate();
    if (day <= n) {
        if (mon > 1) {
            mon = mon - 1;
        } else {
            year = year - 1;
            mon = 12;
        }
    }
    d.setDate(d.getDate() - n);
    year = d.getFullYear();
    mon = d.getMonth() + 1;
    day = d.getDate();
    s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
    return s;
}

export default {
    fromatDate,
    evenNum,
    getQueryStringArgs,
    requestGet,
    requestPost,
    getBeforeDate
}